package com.jigang.study.netty.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * BIO Time Server
 *
 * @author wujigang
 * @date 2019/8/8
 */
public class BIOTimeServer {

    public static void main(String[] args) throws IOException {

        int port = 8080;

        if (args != null && args.length > 0) {

            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.out.println("args 中端口参数异常: " + args[0]);
            }
        }

        ServerSocket server = null;

        try {
            server = new ServerSocket(port);
            System.out.println("The time server is start in port: " + port);

            Socket socket = null;

            while (true) {
                socket = server.accept();

                new Thread(new TimeServerHandler(socket)).start();
            }

        } finally {
            if (server != null) {
                server.close();
                server = null;
            }
        }
    }

}

class TimeServerHandler implements Runnable {

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {

            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);

            String currentTime = null;
            String body = null;

            while (true) {
                body = in.readLine();

                if (body == null) {
                    break;
                }

                System.out.println("The time server receive order : " + body);

                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";

                out.println(currentTime);
            }

        } catch (Exception e) {

        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
